"""此程序只是单独的微信支付成功后,接收腾讯的通知的"""
from django.urls import path
from django.contrib import admin
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import HttpResponse
import xml.etree.ElementTree as ET
import hashlib


def md5(string):
    m = hashlib.md5()
    m.update(string.encode('utf-8'))
    return m.hexdigest()


@csrf_exempt
def pay_notify(request):
    """支付完成后的通知"""
    if request.method == 'POST':
        # 1. 获取结果将xml转换成json
        root = ET.XML(request.body.decode('utf-8'))
        result = {child.tag: child.text for child in root}

        print('腾讯给我们发的数据-> ', result)

        # 2 检验签名是否正确,防止恶意请求
        sign = result.pop('sign')
        pay_key = '20040125ZYFZWD20040125zyfzwd3232'  # key为商户平台设置的密钥key
        temp = "&".join(
            ["{0}={1}".format(k, result[k]) for k in sorted(result)] + ["{0}={1}".format("key", pay_key, ), ])
        local_sign = md5(temp).upper()
        print(sign, local_sign)

        # 签名一致
        if local_sign == sign:
            # 根据订单号, 把数据库的订单状态改为支付成功
            out_trade_no = result.get('out_trade_no')
            # models.Order.objects.filter(uid=out_trade_no).update(status=2)
            response = """
                <xml>
                  <return_code><![CDATA[SUCCESS]]></return_code>
                  <return_msg><![CDATA[OK]]></return_msg>
                </xml>
            """
        else:
            response = """
                <xml>
                  <return_code><![CDATA[FAIL]]></return_code>
                  <return_msg><![CDATA[签名失败]]></return_msg>
                </xml>
            """
        return HttpResponse(response)


urlpatterns = [
    path('admin/', admin.site.urls),
    path('pay/notify/', pay_notify),
]
